<template>
  <div class="login-container">
    <div class="login-form-wrapper">
      <div class="login-box">
        <h2 class="title">云存储系统</h2>
        <div class="subtitle">欢迎回来，请登录您的账户</div>
        
        <form @submit.prevent="handleLogin">
          <div class="form-group" :class="{'error': errors.username}">
            <label for="username">用户名</label>
            <div class="input-wrapper">
              <i class="input-icon">👤</i>
              <input 
                type="text" 
                id="username" 
                v-model.trim="loginForm.user" 
                placeholder="请输入用户名"
                @blur="validateUsername"
                @input="validateUsername"
              />
            </div>
            <div class="error-tip" v-if="errors.username">{{ errors.username }}</div>
          </div>
          
          <div class="form-group" :class="{'error': errors.password}">
            <label for="password">密码</label>
            <div class="input-wrapper">
              <i class="input-icon">🔒</i>
              <input 
                :type="showPassword ? 'text' : 'password'" 
                id="password" 
                v-model="loginForm.password" 
                placeholder="请输入密码"
                @blur="validatePassword"
                @input="validatePassword"
              />
              <i class="toggle-password" @click="showPassword = !showPassword">
                {{ showPassword ? '👁️' : '👁️‍🗨️' }}
              </i>
            </div>
            <div class="error-tip" v-if="errors.password">{{ errors.password }}</div>
          </div>
          
          <div class="form-options">
            <div class="remember-me">
              <input type="checkbox" id="remember" v-model="rememberMe">
              <label for="remember">记住我</label>
            </div>
          </div>
          
          <button 
            type="submit"
            :disabled="loading || !isFormValid" 
            class="login-button"
            :class="{'disabled': !isFormValid}"
          >
            <span v-if="loading" class="loading-spinner">⟳</span>
            <span v-else>登录</span>
          </button>
        </form>
        
        <!-- 错误信息提示 -->
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        
        <!-- 登录状态提示 -->
        <div v-if="loginStatus" class="status-message">
          {{ loginStatus }}
        </div>
        
        <!-- 注册链接 -->
        <div class="register-link">
          还没有账号？<a href="javascript:void(0)" @click="goToRegister">立即注册</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue';
import axios from 'axios';
import md5 from 'md5';
import { useRouter } from 'vue-router';

const router = useRouter();
const loading = ref(false);
const errorMessage = ref('');
const loginStatus = ref('');
const rememberMe = ref(false);
const showPassword = ref(false);

// 表单错误信息
const errors = reactive({
  username: '',
  password: ''
});

const loginForm = reactive({
  user: '',
  password: ''
});

// 检查表单是否有效
const isFormValid = computed(() => {
  return loginForm.user.trim() !== '' && 
         loginForm.password !== '' && 
         !errors.username && 
         !errors.password;
});

// 表单验证方法
const validateUsername = () => {
  if (!loginForm.user.trim()) {
    errors.username = '用户名不能为空';
  } else {
    errors.username = '';
  }
};

const validatePassword = () => {
  if (!loginForm.password) {
    errors.password = '密码不能为空';
  } else {
    errors.password = '';
  }
};

// 从本地存储恢复数据
onMounted(() => {
  const savedUsername = localStorage.getItem('remembered_user');
  if (savedUsername) {
    loginForm.user = savedUsername;
    rememberMe.value = true;
  }
});

const handleLogin = async () => {
  // 验证表单
  validateUsername();
  validatePassword();
  
  if (!isFormValid.value) {
    return;
  }
  
  // 清除之前的错误信息
  errorMessage.value = '';
  
  try {
    loading.value = true;
    
    // MD5加密密码
    const encryptedPwd = md5(loginForm.password);
    
    // 构建请求数据
    const requestData = {
      user: loginForm.user,
      pwd: encryptedPwd
    };
    
    console.log('正在发送登录请求...');
    
    // 直接请求后端地址
    const response = await axios.post('/api/login', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    console.log('登录响应:', response.data);
    
    if (response.data.code === 0) {
      console.log('登录成功，获取到token:', response.data.token);
      
      // 保存认证信息
      localStorage.setItem('token', response.data.token || '');
      localStorage.setItem('user', loginForm.user);
      
      // 如果选择记住我，保存用户名
      if (rememberMe.value) {
        localStorage.setItem('remembered_user', loginForm.user);
      } else {
        localStorage.removeItem('remembered_user');
      }
      
      loginStatus.value = '登录成功，正在跳转...';
      
      // 使用Vue Router导航到首页
      setTimeout(() => {
        router.push('/');
      }, 500);
    } else {
      errorMessage.value = response.data.message || '登录失败，请检查用户名和密码';
      console.error('登录失败:', response.data);
    }
  } catch (error) {
    console.error('登录请求错误:', error);
    errorMessage.value = '登录失败，请稍后重试';
    
    if (error.response) {
      console.error('错误状态:', error.response.status);
      console.error('错误数据:', error.response.data);
    } else if (error.request) {
      console.error('未收到响应');
      errorMessage.value = '服务器未响应，请检查网络连接';
    } else {
      console.error('错误信息:', error.message);
    }
  } finally {
    loading.value = false;
  }
};

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register');
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.login-form-wrapper {
  width: 100%;
  max-width: 420px;
  padding: 20px;
  margin: 0 auto;
}

.login-box {
  background: white;
  padding: 35px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s, box-shadow 0.3s;
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}

.login-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 10px;
  color: #2c3e50;
  font-weight: 600;
  font-size: 24px;
}

.subtitle {
  text-align: center;
  margin-bottom: 30px;
  color: #7f8c8d;
  font-size: 14px;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-group.error .input-wrapper {
  border-color: #e74c3c;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #34495e;
  font-size: 14px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 8px;
  transition: all 0.3s;
  background: #f9f9f9;
}

.input-wrapper:focus-within {
  border-color: #4a90e2;
  box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1);
  background: #fff;
}

.input-icon {
  padding: 0 12px;
  color: #95a5a6;
  font-style: normal;
}

input {
  width: 100%;
  padding: 12px 10px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  background: transparent;
  outline: none;
}

.toggle-password {
  padding: 0 12px;
  cursor: pointer;
  color: #95a5a6;
  font-style: normal;
  user-select: none;
}

.error-tip {
  color: #e74c3c;
  font-size: 12px;
  margin-top: 5px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.remember-me {
  display: flex;
  align-items: center;
  gap: 6px;
}

.remember-me input[type="checkbox"] {
  width: auto;
}

.remember-me label {
  margin-bottom: 0;
  cursor: pointer;
  font-weight: normal;
  font-size: 13px;
}

.login-button {
  width: 100%;
  padding: 12px;
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-button:hover:not(.disabled) {
  background-color: #3a7bc8;
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(74, 144, 226, 0.2);
}

.login-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.login-button.disabled {
  background-color: #a0c3e8;
  cursor: not-allowed;
}

.loading-spinner {
  animation: spin 1s linear infinite;
  font-size: 18px;
  display: inline-block;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.error-message {
  margin-top: 20px;
  color: #e74c3c;
  font-size: 14px;
  text-align: center;
  padding: 10px;
  background-color: rgba(231, 76, 60, 0.1);
  border-radius: 6px;
}

.status-message {
  margin-top: 20px;
  color: #2ecc71;
  font-size: 14px;
  text-align: center;
  padding: 10px;
  background-color: rgba(46, 204, 113, 0.1);
  border-radius: 6px;
}

.register-link {
  margin-top: 25px;
  text-align: center;
  font-size: 14px;
}

.register-link a {
  color: #4a90e2;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s;
}

.register-link a:hover {
  color: #3a7bc8;
  text-decoration: underline;
}
</style> 